﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;


namespace CCPSIP
{
    public class OracleKitRobot
    {
        private const string kOracleServer = "ISENDER.CCP.COM.TW";
        private const string kOracleUserId = "ISENDER";
        private static byte[] kOracleKey = { 0x61, 0x4B, 0x68, 0x4A, 0x4A, 0x46, 0x41, 0x32, 0x73, 0x57, 0x66, 0x45, 0x73, 0x51, 0x7A, 0x30, 0x5A, 0x6D, 0x35, 0x69, 0x77, 0x51, 0x69, 0x39, 0x67, 0x6A, 0x69, 0x56, 0x4E, 0x44 };

        private static string GetConnStrMIS()
        {
            return String.Format(
              "Data Source={0};Persist Security Info=True;User ID={1};Password={2}",
              kOracleServer, kOracleUserId, System.Text.Encoding.UTF8.GetString(kOracleKey));
        }

         /// <summary>
    /// Insert 訊息到 msg_one_robot Table
    /// </summary>
    /// <param name="SendType">發訊類型</param>
    /// <param name="SIP_Num">User SIP帳號</param>
    /// <param name="ROBOT_ID">機器人ID</param>
    /// <param name="SERVICE_ID">機器人服務ID</param>
    /// <param name="MsgID">單人聊天訊息ID</param>
    /// <param name="message">訊息全文</param>
    /// <param name="msgTime">儲存訊息時間</param>
    public static void InsertMsgOneRobot(string SendType, string SIP_Num, string ROBOT_ID, string SERVICE_ID, long MsgID, string message, DateTime msgTime) {
        OracleConnection connOracle = new OracleConnection(GetConnStrMIS());
      try {
        connOracle.Open();
        string insStr = "INSERT INTO msg_one_robot"
          + " (CreateTime, Status, SendType, SIP_Num, ROBOT_ID, SERVICE_ID, MsgID, MsgContent) VALUES"
          + " (:CreateTime, '0', :SendType, :SIP_Num, :ROBOT_ID, :SERVICE_ID, :MsgID, :MsgContent)";
        OracleCommand insCmd = new OracleCommand(insStr, connOracle);
        insCmd.Parameters.Add("CreateTime", OracleType.DateTime).Value = msgTime;
        insCmd.Parameters.Add("SendType", OracleType.VarChar).Value = SendType;
        insCmd.Parameters.Add("SIP_Num", OracleType.VarChar).Value = SIP_Num;
        insCmd.Parameters.Add("ROBOT_ID", OracleType.VarChar).Value = ROBOT_ID;
        insCmd.Parameters.Add("SERVICE_ID", OracleType.VarChar).Value = SERVICE_ID;
        insCmd.Parameters.Add("MsgID", OracleType.Int32).Value = MsgID;
        insCmd.Parameters.Add("MsgContent", OracleType.VarChar).Value = message;
        insCmd.ExecuteNonQuery();
      }
      finally {
        connOracle.Close();
      }
    }


    /// <summary>
    /// 檢查機器人Service是否有回應
    /// </summary>
    /// <param name="SERVICE_ID">機器人服務ID</param>
    /// <param name="SIP_Num">User SIP帳號</param>
    /// <param name="UserReqTime">User傳訊給機器人的時間</param>
    /// <returns>Service有回應為true，否則false</returns>
    public static bool hasReply(string ROBOT_ID, string SERVICE_ID, string SIP_Num, DateTime UserReqTime) {
        OracleConnection connOracle = new OracleConnection(GetConnStrMIS());
      try {
        connOracle.Open();
        string selStr1 = "SELECT COUNT(*) FROM msg_one_robot"
          + " WHERE SendType IN ('R','S') AND CreateTime>=:UserReqTime"
          + "   AND SIP_Num=:SIP_Num"
          + "   AND SERVICE_ID IN (:SERVICE_ID, :ROBOT_ID)";
        OracleCommand selCmd1 = new OracleCommand(selStr1, connOracle);
        selCmd1.Parameters.Add("UserReqTime", OracleType.DateTime).Value = UserReqTime;
        selCmd1.Parameters.Add("SIP_Num", OracleType.VarChar).Value = SIP_Num;
        selCmd1.Parameters.Add("SERVICE_ID", OracleType.VarChar).Value = SERVICE_ID;
        selCmd1.Parameters.Add("ROBOT_ID", OracleType.VarChar).Value = ROBOT_ID;
        UInt32 count = Convert.ToUInt32(selCmd1.ExecuteScalar());
        return (count > 0);
      }
      finally {
        connOracle.Close();
      }
    }


    /// <summary>
    /// 檢查機器人Service是否有回應
    /// </summary>
    /// <param name="param">RobotCheckParam參數物件</param>
    public static void CheckRobotReply(object param) {
      try {
        if (param is RobotCheckParam) {
          const int kMsgPreviewLength = 20;
          System.Threading.Thread.Sleep(121 * 1000);//等待幾分鐘

          RobotCheckParam p = (RobotCheckParam)param;
          RobotServiceInfo rService = p.ServiceInfo;
          string ROBOT_ID = rService.ROBOT_ID;
          string SERVICE_ID = rService.SERVICE_ID;
          string SIP_Num = p.UserInfo.SIP_Num;


          bool hasReply = OracleKitRobot.hasReply(ROBOT_ID, SERVICE_ID, SIP_Num, p.RequestTime);

          if (!hasReply) {
            DateTime replyTime = DateTime.Now;
            string message = string.Format("[{0}]無回應，{1}", rService.SERVICE_NAME, rService.CONTACT_DESC);

            string msgPreview = message;
            if (msgPreview.Length > kMsgPreviewLength)
              msgPreview = msgPreview.Substring(0, kMsgPreviewLength - 3) + "...";
            msgPreview = string.Format("{0}: {1}", rService.ROBOT_CNAME, msgPreview);

            long MsgID = OracleKitMsg.InsertMsgOne(ROBOT_ID, SIP_Num, "T", msgPreview, message, -1, replyTime);
            OracleKitRobot.InsertMsgOneRobot("S", SIP_Num, ROBOT_ID, SERVICE_ID, MsgID, message, replyTime);
            PushKit.WakePushAsync(PushKit.PushType.Msg);
          }
        }
      }
      catch (Exception ex) {
        ChrisKit.SkipVar(ex);
      }
    }


  }


  /// <summary>
  /// 機器人回應檢查Parameters
  /// </summary>
  public class RobotCheckParam
  {
    private SipUserInfo _UserInfo;
    private RobotServiceInfo _ServiceInfo;
    private DateTime _RequestTime;

    public SipUserInfo UserInfo { get { return this._UserInfo; } }
    public RobotServiceInfo ServiceInfo { get { return this._ServiceInfo; } }
    public DateTime RequestTime { get { return this._RequestTime; } }


    public RobotCheckParam(SipUserInfo userInfo, RobotServiceInfo service, DateTime reqTime) {
        _UserInfo = userInfo;
        _ServiceInfo = service;
      _RequestTime = reqTime;
    }
    }
}